package com.zhiqian.rpc;

import com.zhiqian.service.RpcService;
import com.zhiqian.service.ServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

@Slf4j
public class SocketService implements RpcService {
    @Override
    public void start() {

    }

    @Override
    public <T> void publishService(Object object) {

    }

    private final ExecutorService threadPool;
    private static final int CORE_POOL_SIZE=5;
    private static final int MAXIMUM_POOL_SIZE=50;
    private static final int KEEP_ALIVE_TIME=60;
    private static final int BLOCKING_QUEUE_CAPACITY=100;
    private RequestHandler requestHandler=new RequestHandler();
    private final ServiceProvider serviceRegistry;

    public SocketService(ServiceProvider serviceRegistry){
        this.serviceRegistry=serviceRegistry;
        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(BLOCKING_QUEUE_CAPACITY);
        ThreadFactory threadFactory= Executors.defaultThreadFactory();
        threadPool=new ThreadPoolExecutor(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.SECONDS,workingQueue,threadFactory,new ThreadPoolExecutor.AbortPolicy());
    }
    public void start(int port){
        try(ServerSocket serverSocket=new ServerSocket(port)){
            log.info("服务器正在启动....");
            Socket socket;
            while((socket=serverSocket.accept())!=null){
                log.info("客户端连接！ip地址为：{}:{}",socket.getInetAddress(),socket.getPort());
                threadPool.execute(new RequestHandlerThread(socket,requestHandler,serviceRegistry));
            }
            threadPool.shutdown();
        }catch (IOException e){
            log.error("连接时有错误发生：{}",e);
        }
    }
}
